package other.edan.erp.apitool;

import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.exception.CacheException;
import com.rkhd.platform.sdk.exception.CustomConfigException;
import com.rkhd.platform.sdk.http.CommonData;
import com.rkhd.platform.sdk.http.CommonHttpClient;
import com.rkhd.platform.sdk.http.HttpResult;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.service.CacheService;
import com.rkhd.platform.sdk.service.CustomConfigService;
import org.apache.commons.lang.StringUtils;
import other.edan.erp.utils.ResultVo;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description 北森请求
 * @Author 黎炎松
 * 2024-11-08 14:02
 */
public class BsClientUtils {
    private static String BASE_URL = "https://openapi.italent.cn"; // 正式域名
    private static String GET_TOKEN_URL = BASE_URL + "/token"; // 获取token
    public static String GET_USER_ID = BASE_URL + "/TenantBaseExternal/api/v5/Employee/GetUserIDsByMobilesV5"; // 根据手机号获取对应UserID
    public static String GET_USER_INFO = BASE_URL + "/TenantBaseExternal/api/v5/EmpSubset/GetSubsetByUserId"; // 根据员工UserID获取指定员工的指定员工子集相关信息
    private static final Logger logger = LoggerFactory.getLogger();
    private static final CacheService cacheService = CacheService.instance();
    private static final String TOKEN_KEY = "BS_TOKEN";

    // 读取配置
    public static Map<String, String> bsConfig = new HashMap<>();

    static {
        try {
            CustomConfigService instance = CustomConfigService.instance();
            bsConfig = instance.getConfigSet("bsConfig");
            if (bsConfig == null) {
                bsConfig = new HashMap<>();
            }
        } catch (CustomConfigException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws CacheException {
        String str = "{\"jobNumbers\":[\"010295\"]}";
        BsClientUtils.sendPost(JSONObject.parseObject(str), GET_USER_ID, "");

        str = "{\"metaObjectName\":\"jobhistory\",\"oId\":194082028,\"isWithDeleted\":true,\"columns\":null,\"sort\":{\"CreatedTime\":2}}";
        BsClientUtils.sendPost(JSONObject.parseObject(str), GET_USER_INFO, "");

    }

    /**
     * 发送post请求
     * @param reqData
     * @param reqUrl
     * @return
     */
    public static ResultVo sendPost(JSONObject reqData, String reqUrl, String token) throws CacheException {

        if (StringUtils.isBlank(token)) {
            token = getToken();
        }

        CommonData build = CommonData.newBuilder().callString(reqUrl)
                .callType("POST")
                .header("Authorization", "Bearer " + token)
                .body(reqData.toJSONString())
                .build();
        HttpResult execute = CommonHttpClient.instance(1000 * 35, 1000 * 35).execute(build);
        String result = execute.getResult();
        System.out.println("result = " + result);
        JSONObject response = JSONObject.parseObject(result);
        Integer code = response.getInteger("code");
        String message = response.getString("message");

        // 判断缓存 token 是否过期
        if (code == null && message.equals("un-authorized")) {
            // todo 排查 token 过期的返回的值
            // 重新发起请求
            logger.error("北森 token过期，重新发起请求");
            cacheService.delete(TOKEN_KEY);
            return sendPost(reqData, reqUrl, "");
        }

        if (code != 200) {
            String errorMsg = response.getString("msg");
            logger.error("发送请求异常：" + errorMsg);
            return ResultVo.error(errorMsg);
        }

        Object data = response.get("data");
        return ResultVo.success(data);
    }

    // 判断是否能正常解析
    public static boolean isJSON(String str) {
        boolean result = false;
        try {
            JSONObject.parseObject(str);
            result = true;
        } catch (Exception e) {
            result = false;
        }
        return result;
    }


    public static String getToken() throws CacheException {

        // 判断缓存中是否存在
        String token = cacheService.get(TOKEN_KEY);
        if (StringUtils.isNotBlank(token)) {
            logger.info("获取缓存token");
            return token;
        }

        JSONObject reqData = new JSONObject();
        reqData.put("grant_type", "client_credentials");
        reqData.put("app_key", bsConfig.getOrDefault("app_key","ECCE6C9C953A4FD6A1058AA01F61A2FD"));
        reqData.put("app_secret", bsConfig.getOrDefault("app_secret","3F2E93847EA14DB1830046098EED02ECC65A4F381A924091843BAB4D552C8E05"));

        // 发送请求
        CommonData build = CommonData.newBuilder().callString(GET_TOKEN_URL)
                .body(reqData.toString())
                .callType("POST")
                .build();

        HttpResult execute = CommonHttpClient.instance().execute(build);
        String result = execute.getResult();
        logger.info("result ==> " + result);

        // 判断是json 且有 access_token 代表获取成功
        if (!isJSON(result)) {
            throw new RuntimeException("获取token异常:" + result);
        }

        JSONObject response = JSONObject.parseObject(result);
        String accessToken = response.getString("access_token");
        if (StringUtils.isBlank(accessToken)) {
            throw new RuntimeException("获取token异常:" + result);
        }

        // 设置缓存值
        cacheService.set(TOKEN_KEY, accessToken);
        return accessToken;
    }


}
